package com.reading.core.manager.impl;

import com.reading.common.entity.view.BookCollect;
import com.reading.common.persistence.view.BookCollectMapper;
import com.reading.core.exception.AloneException;
import com.reading.core.exception.other.CollectBookFailException;
import com.reading.core.manager.ICollectManager;
import com.reading.core.utils.CheckUtil;
import com.reading.core.utils.GlobalConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author guwenqi_1995@163.com
 * @date 2019/7/9 3:38 PM
 **/
@Slf4j
@Service
public class CollectManagerImpl implements ICollectManager {

    @Resource
    private BookCollectMapper bookCollectMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void collect(Integer bookId, Integer userId) throws AloneException {
        CheckUtil.isNull(bookId, userId);

        //收藏状态。true:以收藏，false:未收藏
        Boolean status = bookCollectMapper.selectCollectStatus(bookId, userId)
                .equals(GlobalConstant.NUMBER_1);

        int row;
        BookCollect collect = new BookCollect(bookId, userId);
        if (status) {
            row = bookCollectMapper.delete(collect);
        } else {
            row = bookCollectMapper.insert(collect);
        }

        if (row <= GlobalConstant.NUMBER_0) {
            log.error("收藏或取消收藏失败。");
            throw new CollectBookFailException();
        }
    }

}
